//
//  CacheManager.swift
//  App_Profile
//
//  Created by 蒋晨成 on 2022/2/9.
//

import Foundation
import Kingfisher

class CacheManager {
    static func calculateDiskStorageSize(completion handler: ((String) -> Void)?) {
        //  [0 - 128) B
        //  [128 - 128 * 1024) KB
        //  [128 * 1024 - 128 * 1024 * 1024) MB
        KingfisherManager.shared.cache.calculateDiskStorageSize { result in
            switch result {
            case .success(let value):
                var size = Double(value)
                var s = ""
                if size < 128 {
                    s = String(format: "%.0fB", size)
                } else if size >= 128, size < 128 * 1024 {
                    size /= 1024
                    s = String(format: "%.1fKB", size)
                } else if size >= 128 * 1024, size < 128 * 1024 * 1024 {
                    size /= (1024 * 1024)
                    s = String(format: "%.1fMB", size)
                } else {
                    size /= (1024 * 1024 * 1024)
                    s = String(format: "%.1fGB", size)
                }
                handler?(s)

            case .failure:
                handler?("0B")
            }
        }
    }

    static func clear(completion handler: (() -> Void)? = nil) {
        KingfisherManager.shared.cache.clearDiskCache {
            handler?()
        }
    }
}
